<?php
/*
Plugin Name: FeedBurner Stats
Plugin URI: http://code.google.com/p/feedburnerstats/
Description: Sends feed requests to the FeedBurner site, allowing you to track your blogs stats.
Version: 0.1.4
Author: Marius Storm-Olsen
Author URI: http://code.google.com/u/mstormo/

Based upon Mark @ 45n5.com's blog:
http://www.45n5.com/permalink/how-to-get-feedburner-stats-without-using-feedburn.html
Licensed under the terms of the <a href="http://www.gnu.org/licenses/gpl.html">GPL</a>
*/

/*  Copyright 2006  Marius Storm-Olsen  (email : mstormo [at] gmail [dot] com)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

$FeedBurnerStats_Debug = 0;
function fbso_debug($txt) {
    global $FeedBurnerStats_Debug;
    if ($FeedBurnerStats_Debug)
        trigger_error($txt);
}

class FeedBurnerStats {

    var $useragent;
    var $useragentrewrite;
    var $useragentignore;
    var $remoteip;
    var $referer;
    var $xmoz;
    var $ifmodifiedsince;
    var $ifnonematch;
    var $feedburnerURL;

    function __construct() {
        fbso_debug("FeedBurner - constructor");
        $this->useragent = $_SERVER['HTTP_USER_AGENT'];
        $this->referer   = $_SERVER['HTTP_REFERER'];
        $this->remoteip  = $_SERVER['REMOTE_ADDR'];
        $this->xmoz      = $_SERVER['HTTP_X-MOZ'];
        $this->ifmodifiedsince = $_SERVER['HTTP_IF-MODIFIED-SINCE'];
        $this->ifnonematch     = $_SERVER['HTTP_IF-NONE-MATCH'];
        $this->feedburnerURL   = get_option('feedburnerstat_url');
        $this->useragentrewrite= get_option('feedburnerstat_useragentrewrite');
        $this->useragentignore = get_option('feedburnerstat_useragentignore');

        # If everything is ok, lets feed those stats!
        if ($this->feedburnerURL != '')
            $this->feedburnerStat();
        else
            fbso_debug("FeedBurner - constructor: missing feedburnerstat_url in database, aborting");
    }

    function feedburnerStat() {
        # User-Agent rewrite
        if ($this->useragentrewrite) {
            $newuseragent = ereg_replace("\)", "; ip=$this->remoteip)", $this->useragent);
            if ($newuseragent == $this->useragent)
                $newuseragent .= " (ip=$this->remoteip)";
            if ($this->useragentignore
                && (ereg("subscriber", $this->useragent)
                   || ereg("feed-id", $this->useragent)))
                ; # Ignore
            else
                $this->useragent = $newuseragent;
        }

        fbso_debug("FeedBurner - burning: remoteip:[$this->remoteip] feed:[$this->feedburnerURL] user_agent:[$this->useragent] referer:[$this->referer]");

        # Setting up proxy headers
        $proxy_headers = array("X-Forwarded-For: $this->remoteip");
        if ($this->referer != '')
            $proxy_headers[] = "Referer: $this->referer";
        if ($this->xmoz != '')
            $proxy_headers[] = "X-Moz: $this->xmoz";
        if ($this->ifmodifiedsince)
            $proxy_headers[] = "If-Modified-Since: $this->ifmodifiedsince";
        if ($this->ifnonematch)
            $proxy_headers[] = "If-None-Match: $this->ifnonematch";

        # "ping" FeedBurner
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->feedburnerURL);
        curl_setopt($ch, CURLOPT_USERAGENT, $this->useragent);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $proxy_headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        curl_close($ch);

        fbso_debug("FeedBurner - burning: done");
    }
}

function on_feeds() {
    fbso_debug("FeedBurner - on_feeds!");
    $fbso = new FeedBurnerStats();
}


# --------------------------------------------------------------------------------------------------
# Plugin configuration pages

function feedburnerstats_option_button() {
    if (function_exists('add_options_page'))
        add_options_page('FeedBurner Stats', 'FeedBurner Stats', 8, basename(__FILE__), 'feedburnerstats_subpanel');
}

function feedburnerstats_subpanel() {
    $default_url = 'http://feeds.feedburner.com/[your feed here]';
    $feedurl = get_option('feedburnerstat_url', $default_url);
    $useragentrewrite = get_option('feedburnerstat_useragentrewrite', false);
    $useragentignore = get_option('feedburnerstat_useragentignore', false);

    if ($feedurl == '')
        $feedurl = $default_url;

    if (isset($_POST['feedburnerstats_options_update'])) {
        if (isset($_POST['FeedBurnerStat_URL'])
            && ($_POST['FeedBurnerStat_URL'] != $feedurl
                || isset($_POST['FeedBurnerStat_UserAgentRewrite']) != $useragentrewrite)
                || isset($_POST['FeedBurnerStat_UserAgentIgnore']) != $useragentignore) {
            update_option('feedburnerstat_url', $_POST['FeedBurnerStat_URL']);
            update_option('feedburnerstat_useragentrewrite', isset($_POST['FeedBurnerStat_UserAgentRewrite']));
            update_option('feedburnerstat_useragentignore', isset($_POST['FeedBurnerStat_UserAgentIgnore']));

            ?> <div id="message" class="updated fade"><p><strong>Options updated successfully!</strong></p></div> <?php
            # Set the feed URL to the updated one
            $feedurl = $_POST['FeedBurnerStat_URL'];
            $useragentrewrite = isset($_POST['FeedBurnerStat_UserAgentRewrite']);
            $useragentignore = isset($_POST['FeedBurnerStat_UserAgentIgnore']);
        } else {
            ?> <div id="message" class="updated"><p><strong>Options not changed</strong></p></div> <?php
        }
    }
?>
<div class='wrap'>
    <table width='100%' cellpadding='0' cellspacing='0'><tr><td>
        <table width='100%' cellpadding='0' cellspacing='0'><tr>
            <td width="50px"><img src="<?php echo get_bloginfo('url') ?>/wp-content/plugins/feedburner_stats/feedburner_flame.png"></td>
            <td valign="bottom"><h2>FeedBurner Stats options</h2></td>
        </tr></table>
        <form method='POST'>
            <ol>
                <li><a href="https://www.feedburner.com/fb/a/addfeed?sourceUrl='<?php echo get_bloginfo('url') ?>'" target="_blank">Create a FeedBurner feed for <?php echo get_bloginfo('name') ?></a></li>
                <li>Then enter the URL to your FeedBurner feed here:<br />
                    <input type='text' name='FeedBurnerStat_URL' value='<?php echo $feedurl ?>' size='70' /><br />
                    If your blog at FeedBurner is password protected, write your URL like this:<br />
                    <code>http://username:password@feeds.feedburner.com/...</code><br /><br />
                    <input type='checkbox' name='FeedBurnerStat_UserAgentRewrite' value='1' <?php if ($useragentrewrite) echo 'checked' ?> /> Enable User-Agent rewrite <font color="#ff4040"><b>(Experimental)</b></font><br />
                    FeedBurner does not seem to acknowledge the X-Forwarded-For proxy header, so
                    turning on this option will rewrite the User-Agent string to also contain the
                    IP number of feed requester. This might help FeedBurner to distinguish requests
                    from identical User-Agents from different IPs.<br />
                    If you feel FeedBurner is reporting too few subscribers on your blog, turn this option on and see if the number increases.<br />

                    <input type='checkbox' name='FeedBurnerStat_UserAgentIgnore' value='1' <?php if ($useragentignore) echo 'checked' ?> /> Ignore User-Agents containing 'subscriber' count or 'feed-id' <font color="#ff4040"><b>(Experimental)</b></font><br />
                    FeedBurner might not like the User-Agent rewrite on agents which fetch feeds
                    for multiple subscribers, and thus report them as only 1 subscriber. Also, if
                    an agent contains a feed-id we really don't need to add the IP number, since
                    the agent is properly identifiable.
                    This option lets you turn off the User-Agent rewrite for agents which report
                    'subscriber' or 'feed-id'.<br />
                    </li>
            </ol>
            <input type='submit' name='feedburnerstats_options_update' value='Update URL' />
        </form>

    </td></tr></table>
</div>
<?php
}


# --------------------------------------------------------------------------------------------------
# Adding plugin hooks
add_action('admin_menu', 'feedburnerstats_option_button');
add_action('do_feed_rss',  'on_feeds');
add_action('do_feed_rss2', 'on_feeds');
add_action('do_feed_rdf',  'on_feeds');
add_action('do_feed_atom', 'on_feeds');
?>
